package com.kawins.spring;

import com.kawins.spring.valid.util.ValidUtil;
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;

import java.beans.PropertyEditorSupport;

/**
 * 类型转化类,防止跨脚本攻击，往web页面注入html代码或者script代码
 *
 * @author rankai
 *         createTime 2017-04-2017/4/20 14:47
 */
public class StringEscapeEditor extends PropertyEditorSupport {
    /**
     * 编码HTML
     */
    private boolean escapeHTML;
    /**
     * 编码JavaScript
     */
    private boolean escapeJavaScript;
    /**
     * 过滤json
     */
    private boolean escapeJson;

    public StringEscapeEditor() {
        super();
    }

    public StringEscapeEditor(boolean escapeJson, boolean escapeHTML, boolean escapeJavaScript) {
        super();
        this.escapeJson = escapeJson;
        this.escapeHTML = escapeHTML;
        this.escapeJavaScript = escapeJavaScript;
    }

    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }

    @Override
    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            if (escapeJson && ValidUtil.validJson(text)) {
                setValue(text);
            } else {
                String value = text;
                if (escapeHTML) {
                    value = HtmlUtils.htmlEscape(value);
                }
                if (escapeJavaScript) {
                    value = JavaScriptUtils.javaScriptEscape(value);
                }
                setValue(value);
            }
        }
    }
}
